package ServerConnection;

import Client.ServerInfo;
import Message.AccountAddFriendInfo;
import utils.AccountAddFriendInfoList;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;


/**
 * 该类用来调用ThreadHandleReturnFriendRequest，实现返回好友申请给用户，响应客户端的是否有自己的好友申请轮询
 */
public class ReturnFriendRequestServer {
    public static void main(String[] args) {
        try {
            DatabaseServer databaseServer = new DatabaseServer();
            ServerSocket serverSocket = new ServerSocket(ServerInfo.SERVER_SENDREQUESTSREGULARLYTOGETFRIENDREQUEST_PORT);
            System.out.println("返回添加好友申请服务成功启动！");
            Socket socket;
            while (true) {
                socket = serverSocket.accept();
                Thread handle = new Thread(new ThreadHandleReturnFriendRequest(socket, databaseServer));
                handle.start();
            }
        } catch (IOException e) {
            System.out.println("WARNING:ReturnFriendRequestServer Init fail,Reason:socket has ioException.");
        }
    }
}

/**
 * 该类用来新建线程返回某一用户的好友申请，响应客户端的是否有自己的好友申请轮询
 */
 class ThreadHandleReturnFriendRequest implements Runnable {
    Socket socket = null;
    DatabaseServer databaseServer;

    public ThreadHandleReturnFriendRequest(Socket socket, DatabaseServer databaseServer) {
        super();
        this.socket = socket;
        this.databaseServer = databaseServer;
    }

    @Override
    public void run() {
        try {
            System.out.println("收到用户的回复好友申请的请求，正在处理");
            //获取从客户端得到的消息，并且执行了消息。
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);//包装成字符流，提高效率
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);//缓冲区
            String userId = bufferedReader.readLine();//获得用户id

            String sql = String.format("SELECT * FROM FriendRequest WHERE `To`='%s'" + "AND Response=0;", userId);
            String sqlToSetFriendResponse = String.format("UPDATE FriendRequest\n" +
                    "SET Response = (\n" +
                    "CASE \n" +
                    "WHEN `To` = %s THEN 1\n" +
                    "END\n" +
                    ") WHERE Response=0 and `To` IN (%s);", userId, userId);
            ResultSet rs = databaseServer.returnResultSet(sql);

            int numberOfFriendRequest = 0;
            AccountAddFriendInfoList accountAddFriendInfoList = new AccountAddFriendInfoList();
            while (rs.next()) {
                String From = rs.getString("From");
                String To = rs.getString("To");
                Timestamp time = rs.getTimestamp("When");
                String Info = rs.getString("Info");
                AccountAddFriendInfo accountAddFriendInfo = new AccountAddFriendInfo(From, To, Info, time);
                System.out.println(accountAddFriendInfo.getInfo());
                accountAddFriendInfoList.add(accountAddFriendInfo);
            }
            Boolean result = databaseServer.doExecute(sqlToSetFriendResponse);
            System.out.println("result:" + result);

            //返还执行的结果到客户端。
            OutputStream outputStream = socket.getOutputStream(); //获取一个输出流，向服务端发送信息
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(accountAddFriendInfoList);

            inputStream.close();
            objectOutputStream.close();
            outputStream.close();
            //socket.close();


        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }
    }
}
